package cn.sccdlg.ssm.dao;

import cn.sccdlg.ssm.domain.Role;
import cn.sccdlg.ssm.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/10/27 21:25
 * 系统用户持久层
 */
@Repository
@Mapper
public interface IUserDao {

    /**
     * 根据用户名查询用户信息
     * @param username 用户名
     */
    @Select("SELECT * FROM user WHERE username=#{username}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.sccdlg.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findByUsername(String username) throws Exception;

    /**
     * 查询所有用户
     */
    @Select("SELECT * FROM user")
    List<UserInfo> findAll() throws Exception;

    /**
     * 保存用户信息
     * @param userInfo 用户信息
     * @throws Exception
     */
    @Insert("INSERT INTO user(id,email,username,password,phoneNum,status) " +
            "VALUES(#{id},#{email},#{username},#{password},#{phoneNum},#{status})")
    void save(UserInfo userInfo) throws Exception;

    @Select("SELECT * FROM user WHERE id=#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles",column = "id",javaType = java.util.List.class,
                    many = @Many(select = "cn.sccdlg.ssm.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findById(String id) throws Exception;

    /**
     * 根据用户id查询未拥有的用户角色
     * @param userId 用户id
     * @return
     */
    @Select("SELECT * FROM role WHERE id NOT IN (SELECT roleId FROM user_role WHERE userId=#{userId})")
    List<Role> findOtherRoles(String userId);

    /**
     * 保存用户与角色关联关系
     * @param userId 用户id
     * @param roleId 角色id
     */
    @Insert("INSERT INTO user_role(userId,roleId) VALUES(#{userId},#{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);
}
